<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + this.teacherId }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>班级申请审核</el-breadcrumb-item>
    </el-breadcrumb>
    
    <!--卡片视图区域-->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>班级申请审核</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="returnToClassList">返回班级列表</el-button>
      </div>
      
      <!-- 班级选择 -->
      <el-form :inline="true" class="demo-form-inline" style="margin-bottom: 20px">
        <el-form-item label="选择班级">
          <el-select v-model="currentClassId" placeholder="请选择班级" @change="classChanged">
            <el-option
              v-for="item in myClasses"
              :key="item.classId"
              :label="item.className"
              :value="item.classId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请状态">
          <el-select v-model="queryStatus" placeholder="申请状态" @change="getApplicationList">
            <el-option label="全部" value=""></el-option>
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="已通过" value="approved"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <!-- 申请列表 -->
      <el-table :data="applicationList" border stripe v-loading="loading">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="studentName" label="学生姓名" width="120"></el-table-column>
        <el-table-column prop="studentId" label="学号" width="150"></el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.status === 'pending'">待审核</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === 'approved'">已通过</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 'rejected'">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="申请理由"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="success" 
              @click="handleApplication(scope.row, 'approved')"
              :disabled="scope.row.status !== 'pending'">通过</el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="handleApplication(scope.row, 'rejected')"
              :disabled="scope.row.status !== 'pending'">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据提示 -->
      <el-empty v-if="applicationList.length === 0" description="暂无申请记录"></el-empty>
    </el-card>
    
    <!-- 处理申请对话框 -->
    <el-dialog :title="handleTitle" :visible.sync="handleDialogVisible" width="40%">
      <el-form :model="handleForm" :rules="handleFormRules" ref="handleFormRef" label-width="100px">
        <el-form-item label="学生姓名">
          <el-input v-model="handleForm.studentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="handleForm.studentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="申请理由">
          <el-input type="textarea" v-model="handleForm.reason" disabled :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="审核备注" prop="remark">
          <el-input type="textarea" v-model="handleForm.remark" :rows="3" placeholder="请输入审核备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDialogVisible = false">取 消</el-button>
        <el-button :type="handleForm.status === 'approved' ? 'success' : 'danger'" @click="submitHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ClassApplications',
  data() {
    return {
      teacherId: sessionStorage.getItem('userID'),
      // 我的班级列表
      myClasses: [],
      // 当前选中的班级ID
      currentClassId: '',
      // 当前查询的申请状态
      queryStatus: '',
      // 申请列表
      applicationList: [],
      // 加载状态
      loading: false,
      // 处理申请对话框
      handleDialogVisible: false,
      handleTitle: '审核申请',
      // 处理申请表单
      handleForm: {
        applicationId: '',
        studentName: '',
        studentId: '',
        reason: '',
        status: '',
        remark: ''
      },
      // 表单验证规则
      handleFormRules: {
        remark: [
          { required: true, message: '请输入审核备注', trigger: 'blur' },
          { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getMyClasses()
  },
  methods: {
    // 获取我的班级列表
    async getMyClasses() {
      try {
        const { data: res } = await this.$http.get('/class/listByTeacher', {
          params: {
            teacherId: this.teacherId
          }
        })
        
        if (res.code === 200) {
          this.myClasses = res.data || []
          
          // 如果有班级，默认选择第一个
          if (this.myClasses.length > 0) {
            this.currentClassId = this.myClasses[0].classId
            this.getApplicationList()
          }
        } else {
          this.$message.error('获取班级列表失败')
        }
      } catch (error) {
        console.error('获取班级列表失败', error)
        this.$message.error('获取班级列表失败')
      }
    },
    
    // 班级变更
    classChanged() {
      this.getApplicationList()
    },
    
    // 获取申请列表
    async getApplicationList() {
      if (!this.currentClassId) return
      
      this.loading = true
      try {
        const { data: res } = await this.$http.get(`/class/application/class/${this.currentClassId}`, {
          params: {
            status: this.queryStatus
          }
        })
        
        if (res.code === 200) {
          this.applicationList = res.data || []
        } else {
          this.$message.error('获取申请列表失败')
        }
      } catch (error) {
        console.error('获取申请列表失败', error)
        this.$message.error('获取申请列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 处理申请
    handleApplication(row, status) {
      this.handleForm = {
        applicationId: row.applicationId,
        studentName: row.studentName,
        studentId: row.studentId,
        reason: row.reason,
        status: status,
        remark: ''
      }
      
      this.handleTitle = status === 'approved' ? '通过申请' : '拒绝申请'
      this.handleDialogVisible = true
    },
    
    // 提交处理结果
    submitHandle() {
      this.$refs.handleFormRef.validate(async valid => {
        if (!valid) return
        
        try {
          const params = {
            status: this.handleForm.status,
            remark: this.handleForm.remark,
            teacherId: this.teacherId
          }
          
          const { data: res } = await this.$http.put(`/class/application/handle/${this.handleForm.applicationId}`, params)
          
          if (res.code === 200) {
            this.$message.success('申请处理成功')
            this.handleDialogVisible = false
            this.getApplicationList()
          } else {
            this.$message.error(res.message || '申请处理失败')
          }
        } catch (error) {
          console.error('申请处理失败', error)
          this.$message.error('申请处理失败')
        }
      })
    },
    
    // 返回班级列表
    returnToClassList() {
      this.$router.push('/manage/' + this.teacherId + '/class')
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style>
